Unit-1,2,3 Extra Programs

Manish Patel

Nov 20, 2023

PATTERN PROGRAM

size = int(input( 'Enter size  = '))
for i in range(1, size):
    for j in range(1,size):
        if (i==j):
            print('$', end = " ")
        elif(i==1 or i==(size-1) or j==1 or j==(size-1)):
             print("*", end=" ")
        else:
             print(" ", end = " ")
    print('\n')
Enter size  = 6
$ * * * * 

* $     * 

*   $   * 

*     $ * 

* * * * $ 

A PATTERN

height = 5
# Number of character width in each line 
width = (2 * height) - 1

def printA(): 
  
    n = width // 2
    for i in range(0, height): 
        for j in range(0, width+1): 
            if (j == n or j == (width - n) or (i == (height // 2) \
                                               and j > n and j < (width - n))): 
                print("*", end="") 
            else: 
                print(end=" ") 
        print() 
        n = n-1
printA()
    **    
   *  *   
  ******  
 *      * 
*        *

PASCAL TRIANGLE

def solve(n):
   for i in range(n+1):
      for j in range(n-i):
         print(' ', end='')

      C = 1
      for j in range(1, i+1):
         print(C, ' ', sep='', end='')
         C = C * (i - j) // j
      print()

n = 5
solve(n)
     
    1 
   1 1 
  1 2 1 
 1 3 3 1 
1 4 6 4 1 

Write a program that given an amount of change less than one dollar will print out exactly how many quarters, dimes, nickels, and pennies will be needed to efficiently make that change. In the context of United States currency:

  • Quarter: A coin worth 25 cents.
  • Dime: A coin worth 10 cents.
  • Nickel: A coin worth 5 cents.
  • Penny: A coin worth 1 cent.

def make_change(amount):
    remaining_cents = int(amount * 100)

    quarters = remaining_cents // 25
    remaining_cents %= 25

    dimes = remaining_cents // 10
    remaining_cents %= 10

    nickels = remaining_cents // 5
    remaining_cents %= 5

    pennies = remaining_cents

    print("Quarters:", quarters)
    print("Dimes:", dimes)
    print("Nickels:", nickels)
    print("Pennies:", pennies)

# Get user input for the amount of change
change_amount = float(input("Enter the amount of change (less than $1.00): "))

# Call the function to calculate and print the change
make_change(change_amount)
Enter the amount of change (less than $1.00): 0.72
Quarters: 2
Dimes: 2
Nickels: 0
Pennies: 2

Write a program to compute the sum 1-2+3-4+…+1999-2000.

def compute_sum():
    total_sum = 0
    for i in range(1, 2001):
        if i % 2 == 0:
            total_sum -= i
        else:
            total_sum += i
    return total_sum

result = compute_sum()
print("The sum 1-2+3-4+...+1999-2000 is:", result)
The sum 1-2+3-4+...+1999-2000 is: -1000

INTEGER TO ROMAN

def int_to_roman(num):
    thousands = num // 1000
    num %= 1000
    hundreds = num // 100
    num %= 100
    tens = num // 10
    ones = num % 10

    roman_numeral = 'M' * thousands

    if hundreds == 9:
        roman_numeral += 'CM'
    elif hundreds >= 5:
        roman_numeral += 'D' + 'C' * (hundreds - 5)
    elif hundreds == 4:
        roman_numeral += 'CD'
    else:
        roman_numeral += 'C' * hundreds

    if tens == 9:
        roman_numeral += 'XC'
    elif tens >= 5:
        roman_numeral += 'L' + 'X' * (tens - 5)
    elif tens == 4:
        roman_numeral += 'XL'
    else:
        roman_numeral += 'X' * tens

    if ones == 9:
        roman_numeral += 'IX'
    elif ones >= 5:
        roman_numeral += 'V' + 'I' * (ones - 5)
    elif ones == 4:
        roman_numeral += 'IV'
    else:
        roman_numeral += 'I' * ones

    return roman_numeral

# Test the function
number = int(input("Enter an integer: "))
roman_result = int_to_roman(number)
print(f"The Roman numeral for {number} is: {roman_result}")
Enter an integer: 423
The Roman numeral for 423 is: CDXXIII

Write a program to calculate the bill amount for an item given its quantity sold, value, discount, and tax.

def calculate_bill_amount(quantity, value, discount, tax):
    total_cost = quantity * value
    discounted_cost = total_cost - (total_cost * discount / 100)
    total_amount = discounted_cost + (discounted_cost * tax / 100)
    return total_amount

# Get input from the user
quantity = float(input("Enter the quantity sold: "))
value = float(input("Enter the value of the item: "))
discount = float(input("Enter the discount percentage: "))
tax = float(input("Enter the tax percentage: "))

# Calculate and display the bill amount
bill_amount = calculate_bill_amount(quantity, value, discount, tax)
print(f"The total bill amount is: {bill_amount}")
Enter the quantity sold: 3
Enter the value of the item: 30
Enter the discount percentage: 90
Enter the tax percentage: 10
The total bill amount is: 9.9

RECURSIVE GCD

def GCD(x,y):
    rem = x%y
    if (rem==0):
        return y
    else:
        return GCD(y,rem)
n = int(input ("Enter the first number : "))
m = int(input ("Enter the second number : "))
print(f"The GCD of numbers {n} and {m} is {GCD(n,m)}")
Enter the first number : 8
Enter the second number : 24
The GCD of numbers 8 and 24 is 8

Write a program to sum the series 1/1! + 4/2! + 27/3! + …

def fact(n):
    f = 1
    if(n==0 or n==1):
        return 1
    else:
        for i in range(1, int(n+1)):
            f=f*i
    return f

n = int(input('Enter the value of n : '))
s = 0.0
for i in range(1,n+1):
    s = s+(float(i**i)/fact(i))
print("Result :",s)
Enter the value of n : 10
Result : 4511.870240850971

Suppose you put 1Rs in a bank on first day say Monday. And every day from next day, Tuesday to Sunday, you put in 1Rs more than the day before. And on every subsequent Monday, you will put in 1Rs more than the previous Monday. If we have a number n, we have to find the total amount of money you will have in the bank at the end of the nth day.

if the input is like n = 17, then the output will be 75 because, put 1Rs on Monday, 2Rs on Tuesday and so on, so 7Rs on Sunday, then on next Monday put 2Rs, on second Tuesday put 3Rs, so on Sunday put 8Rs. Then on third Monday put 3Rs, Tuesday put 4Rs and Wednesday (last day) put 5Rs, so total sum is (1+2+3+4+5+6+7)+(2+3+4+5+6+7+8)+(3+4+5) = 75Rs

def solve(n):
   s = 28
   res = 0
   if n>7:
      res = s
      div = n//7
      for i in range(1,div):
         res += s+7*i
      rem = n % 7
      for i in range(1,rem+1):
         res += i+div
   else:
      for i in range(1,n+1):
         res+=i
   return res

n = 17
print(solve(n))
75

GEOMETRIC SERIES

\[ S = 1 + \frac{1}{2} + \frac{1}{4} + \frac{1}{8} + \ldots \]

# Function to calculate the sum of a geometric series
def geometric_series_sum(r, n):
    return 1 / (1 - r)

# Common ratio for the series
common_ratio = 1/2

# Number of terms in the series (adjust as needed)
num_terms = 1000

# Calculate the sum of the geometric series
sum_result = geometric_series_sum(common_ratio, num_terms)

print(f"The sum of the series is: {sum_result}")
The sum of the series is: 2.0

NTH PRIME NUMBER

def is_prime(num):
    if num < 2:
        return False
    for i in range(2, int(num**0.5) + 1):
        if num % i == 0:
            return False
    return True

def nth_prime_number(n):
    prime_count = 0
    num = 2

    while True:
        if is_prime(num):
            prime_count += 1
            if prime_count == n:
                return num
        num += 1

# Find the 10th prime number as an example
nth_prime = 15
result = nth_prime_number(nth_prime)

print(f"The {nth_prime}th prime number is: {result}")
The 15th prime number is: 47

Write a program to sum the series -

\[1/1 +2^{2}/2 + 3^{3}/3+... +n^{n}/n\]

n = int ( input ( "Enter the value of n : " ))
s = 0.0
for i in range(1,n+1):
    a = float(i**i)/i
    s = s+a
print(f'The sum of the series is ',s)
Enter the value of n : 5
The sum of the series is  701.0

FIND SMALLEST POSITIVE NUMBER DIVISIBLE BY 1 TO 10

def find_smallest_number():
    number = 1
    found = False
    
    while not found:
        found = True
        for i in range(1, 11):
            if number % i != 0:
                found = False
                break
        if not found:
            number += 1

    return number

result = find_smallest_number()
print("The smallest positive number divisible by integers from 1 to 10 is:", result)
The smallest positive number divisible by integers from 1 to 10 is: 2520

REDUCE FRACTION PROBLEM

def gcd(x, y):
    # Calculate the greatest common divisor using Euclidean algorithm
    while y:
        x, y = y, x % y
    return x

def reduce_fraction(numerator, denominator):
    # Find the greatest common divisor
    common_divisor = gcd(numerator, denominator)

    # Reduce the fraction by dividing both numerator and denominator by the common divisor
    reduced_numerator = numerator // common_divisor
    reduced_denominator = denominator // common_divisor

    return reduced_numerator, reduced_denominator

# Input numerator and denominator
numerator = int(input("Enter the numerator: "))
denominator = int(input("Enter the denominator: "))

# Check if the fraction is valid (denominator should not be zero)
if denominator != 0:
    # Reduce the fraction
    reduced_numerator, reduced_denominator = reduce_fraction(numerator, denominator)

    # Display the reduced fraction
    print(f"The reduced fraction is: {reduced_numerator}/{reduced_denominator}")

else:
    print("Invalid fraction. Denominator cannot be zero.")
Enter the numerator: 25
Enter the denominator: 5
The reduced fraction is: 5/1

Implement Babylonian method to find squareroot of a given number

  • The Babylonian method for finding square roots is an iterative algorithm that refines an initial guess to approach the actual square root of a given number.

image.png

def babylonian_sqrt(number, iterations=10):
    guess = number / 2  # Initial guess

    for _ in range(iterations):
        # Update the guess using the Babylonian method formula
        guess = 0.5 * (guess + number / guess)

    return guess

# Input a number from the user
number = float(input("Enter a number to find its square root: "))

# Check if the number is non-negative
if number >= 0:
    # Calculate and print the square root using the Babylonian method
    square_root = babylonian_sqrt(number)
    print(f"The square root of {number} is approximately: {square_root}")
else:
    print("Invalid input. Please enter a non-negative number.")
Enter a number to find its square root: 2
The square root of 2.0 is approximately: 1.414213562373095

Write a program, which will find all such numbers between 1000 and 3000 (both included) such that each digit of the number is an even number. The numbers obtained should be printed in a comma-separated sequence on a single line.

def are_all_digits_even(num):
    while num > 0:
        digit = num % 10
        if digit % 2 != 0:
            return False
        num //= 10
    return True

def find_and_print_even_digit_numbers(start, end):
    first = True
    for i in range(start, end + 1):
        if are_all_digits_even(i):
            if not first:
                print(",", end="")
            first = False
            print(i, end="")
    print()

start_range = 1000
end_range = 3000
find_and_print_even_digit_numbers(start_range, end_range)
2000,2002,2004,2006,2008,2020,2022,2024,2026,2028,2040,2042,2044,2046,2048,2060,2062,2064,2066,2068,2080,2082,2084,2086,2088,2200,2202,2204,2206,2208,2220,2222,2224,2226,2228,2240,2242,2244,2246,2248,2260,2262,2264,2266,2268,2280,2282,2284,2286,2288,2400,2402,2404,2406,2408,2420,2422,2424,2426,2428,2440,2442,2444,2446,2448,2460,2462,2464,2466,2468,2480,2482,2484,2486,2488,2600,2602,2604,2606,2608,2620,2622,2624,2626,2628,2640,2642,2644,2646,2648,2660,2662,2664,2666,2668,2680,2682,2684,2686,2688,2800,2802,2804,2806,2808,2820,2822,2824,2826,2828,2840,2842,2844,2846,2848,2860,2862,2864,2866,2868,2880,2882,2884,2886,2888

The 3D Euclidean distance is a measure of the straight-line distance between two points in three-dimensional space. It is based on the Euclidean distance formula, which is an extension of the Pythagorean theorem to multiple dimensions.

For two points $ P(x_1, y_1, z_1) and Q(x_2, y_2, z_2) $ in 3D space, the Euclidean distance (d) is calculated using the formula:

\[ d = \sqrt{(x_2 - x_1)^2 + (y_2 - y_1)^2 + (z_2 - z_1)^2}\]

This formula involves taking the square of the differences between corresponding coordinates, summing them up, and then taking the square root of the result. The distance represents the length of the straight line segment connecting the two points in 3D space.Take coordinates as user inputs and find the distance between two points in python

def euclidean_distance(x1, y1, z1, x2, y2, z2):
    distance = ((x2 - x1)**2 + (y2 - y1)**2 + (z2 - z1)**2)**0.5
    return distance

# Input from user for Point P
x1 = float(input("Enter the x-coordinate of Point P: "))
y1 = float(input("Enter the y-coordinate of Point P: "))
z1 = float(input("Enter the z-coordinate of Point P: "))

# Input from user for Point Q
x2 = float(input("Enter the x-coordinate of Point Q: "))
y2 = float(input("Enter the y-coordinate of Point Q: "))
z2 = float(input("Enter the z-coordinate of Point Q: "))

# Calculate Euclidean distance using the function
distance = euclidean_distance(x1, y1, z1, x2, y2, z2)

# Display the result
print(f"The Euclidean distance between Point P and Point Q is: {distance}")
Enter the x-coordinate of Point P: 2
Enter the y-coordinate of Point P: 2
Enter the z-coordinate of Point P: 2
Enter the x-coordinate of Point Q: 8
Enter the y-coordinate of Point Q: 8
Enter the z-coordinate of Point Q: 8
The Euclidean distance between Point P and Point Q is: 10.392304845413264

Write a program that finds all integer solutions to Pell’s equation \[ {x^{2}-2y^2=1}\], where x and y are between 1 and 100.

def pells_equation():
    for x in range(1, 101):
        for y in range(1, 101):
            if x**2 - 2*y**2 == 1:
                print(f"Integer solution: x = {x}, y = {y}")

# Find and print solutions
pells_equation()
Integer solution: x = 3, y = 2
Integer solution: x = 17, y = 12
Integer solution: x = 99, y = 70

STRONG NUMBERS

  • In number theory, a strong number (or digital factorial) is a number such that the sum of its individual digits, each raised to the factorial power, is equal to the number itself.

def factorial(n):
    result = 1
    for i in range(1, n + 1):
        result *= i
    return result

def is_strong_number(number):
    sum_of_factorials = 0
    temp_number = number

    while temp_number > 0:
        digit = temp_number % 10
        sum_of_factorials += factorial(digit)
        temp_number //= 10

    return sum_of_factorials == number

# Input from user
start_range = int(input("Enter the starting number of the range: "))
end_range = int(input("Enter the ending number of the range: "))

# Print strong numbers within the specified range
strong_numbers_found = False
print(f"Strong numbers between {start_range} and {end_range} are:")
for num in range(start_range, end_range + 1):
    if is_strong_number(num):
        print(num, end=" ")
        strong_numbers_found = True

# Check if any strong numbers were found
if not strong_numbers_found:
    print(f"There are no strong numbers between {start_range} and {end_range}.")
Enter the starting number of the range: 1
Enter the ending number of the range: 200
Strong numbers between 1 and 200 are:
1 2 145 

AMICABLE NUMBERS

(220, 284):

Divisors of 220: 1, 2, 4, 5, 10, 11, 20, 22, 44, 55, 110 (Sum = 284)
Divisors of 284: 1, 2, 4, 71, 142 (Sum = 220)

def sum_of_divisors(number):
    divisors_sum = 0
    for divisor in range(1, number):
        if number % divisor == 0:
            divisors_sum += divisor
    return divisors_sum

def are_amicable_numbers(num1, num2):
    return sum_of_divisors(num1) == num2 and sum_of_divisors(num2) == num1

# Input from user
start_range = int(input("Enter the starting number of the range: "))
end_range = int(input("Enter the ending number of the range: "))

# Find and print amicable number pairs within the specified range
amicable_pairs_found = False
print(f"Amicable number pairs between {start_range} and {end_range} are:")
for num1 in range(start_range, end_range + 1):
    for num2 in range(num1 + 1, end_range + 1):
        if are_amicable_numbers(num1, num2):
            print(f"({num1}, {num2})", end=" ")
            amicable_pairs_found = True

# Check if any amicable number pairs were found
if not amicable_pairs_found:
    print(f"There are no amicable number pairs between {start_range} and {end_range}.")
Enter the starting number of the range: 1
Enter the ending number of the range: 300
Amicable number pairs between 1 and 300 are:
(220, 284) 

PERFECT NUMBER

A number is called a perfect number if it is equal to the sum of all of its divisors, not including the number itself. For instance, 6 is a perfect number because the divisors of 6 are 1, 2, 3, 6 and 6=1+2+3. As another example, 28 is a perfect number because its divisors are 1, 2, 4, 7, 14, 28 and 28=1+2+4+7+14. However, 15 is not a perfect number because its divisors are 1, 3, 5, 15 and 15≠1+3+5. Write a program that finds all four of the perfect numbers that are less than 10000.

def is_perfect_number(number):
    if number <= 0:
        return False
    
    sum_of_divisors = 0
    for divisor in range(1, number):
        if number % divisor == 0:
            sum_of_divisors += divisor
    
    return sum_of_divisors == number

# Input from user
start_range = int(input("Enter the starting number of the range: "))
end_range = int(input("Enter the ending number of the range: "))

# Print perfect numbers within the specified range
perfect_numbers_found = False
print(f"Perfect numbers between {start_range} and {end_range} are:")
for num in range(start_range, end_range + 1):
    if is_perfect_number(num):
        print(num, end=" ")
        perfect_numbers_found = True

# Check if any perfect numbers were found
if not perfect_numbers_found:
    print(f"There are no perfect numbers between {start_range} and {end_range}.")
Enter the starting number of the range: 1
Enter the ending number of the range: 50
Perfect numbers between 1 and 50 are:
6 28 

HARSHAD NUMBER

a Harshad number (or Niven number) is a positive integer that is divisible by the sum of its digits.

def is_harshad_number(n):
    # Check if the number is positive
    if n <= 0:
        return False

    # Calculate the sum of digits
    digit_sum = 0
    for digit in str(n):
        digit_sum += int(digit)

    # Check if the number is divisible by the sum of its digits
    return n % digit_sum == 0

# Example usage:
number = int(input("Enter a number: "))
result = is_harshad_number(number)

if result:
    print(f"{number} is a Harshad number.")
else:
    print(f"{number} is not a Harshad number.")
Enter a number: 18
18 is a Harshad number.

SQUAREFREE NUMBER

An integer is called squarefree if it is not divisible by any perfect squares other than 1. For instance, 42 is squarefree because its divisors are 1, 2, 3, 6, 7, 21, and 42, and none of those numbers (except 1) is a perfect square. On the other hand, 45 is not squarefree because it is divisible by 9, which is a perfect square. Write a program that asks the user for an integer and tells them if it is squarefree or not.

def is_squarefree(num):
    if num < 1:
        return False

    for i in range(2, int(num**0.5) + 1):
        if num % (i**2) == 0:
            return False

    return True

# Get user input
user_integer = int(input("Enter an integer to check if it is squarefree: "))

# Check and print the result
if is_squarefree(user_integer):
    print(f"{user_integer} is squarefree.")
else:
    print(f"{user_integer} is not squarefree.")
Enter an integer to check if it is squarefree: 42
42 is squarefree.

HAPPY NUMBERS

A happy number is a number defined by the following process:

Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number either equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1.

For example:

  • 77 -> 49, 44 + 9*9 -> 97
  • 7 => 49 => 97 => 130 => 10 => 1 => Happy!
  • 2 => 4 => 16 => 37 => 58 => 89 => 145 => 42 => 20 => 4 => Loop encountered => Not Happy!

for n in range(1, 30):
    res = n

    while res != 1 and res != 4:
        r = s = 0
        while res > 0:
            r = res % 10
            s += r**2
            res //= 10
        
        res = s

    if res == 1:
        print(n, end = " ")
#     elif res == 4:
#         print(f"{n} is not a happy number")
1 7 10 13 19 23 28 

PRONIC NUMBERS

Program to print all Pronic numbers between 1 and 100

  • The pronic number can be defined as the number which is a product of two consecutive numbers.

#isPronicNumber() will determine whether a given number is a pronic number or not  
def isPronicNumber(num):  
    flag = False;  
      
    for j in range(1, num+1):  
        #Checks for pronic number by multiplying consecutive numbers  
        if((j*(j+1)) == num):  
            flag = True;  
            break;  
    return flag;  
   
#Displays pronic numbers between 1 and 100  
print("Pronic numbers between 1 and 100: ");  
for i in range(1, 101):  
    if(isPronicNumber(i)):  
        print(i, sep= ",", end=" ")
Pronic numbers between 1 and 100: 
2 6 12 20 30 42 56 72 90 

DISARIUM NUMBER

A number is said to be Disarium if the sum of its digits raised to their respective positions is the number itself. Create a function that determines whether a number is a Disarium or not. is_disarium(135) ➞ True 1^1 + 3^2 + 5^3 = 1 + 9 + 125 = 135

# Function to calculate the length (number of digits) of a given number
def calculateLength(n):
    length = 0  # Initialize the length variable to zero
    while(n != 0):  # Loop until the number becomes zero
        length = length + 1  # Increment the length for each digit
        n = n // 10  # Remove the last digit from the number
    return length  # Return the calculated length


num = 246  # Example number
rem = sum = 0  # Initialize variables for remainder and sum
len = calculateLength(num)  # Calculate the length of the number

# Make a copy of the original number 'num'
n = num

# Calculate the sum of digits powered with their respective position
while(num > 0):
    rem = num % 10  # Get the last digit of the number
    sum = sum + int(rem ** len)  # Add the digit powered with its position to the sum
    num = num // 10  # Remove the last digit from the number
    len = len - 1  # Decrease the position for the next digit

# Check whether the sum is equal to the original number
if(sum == n):
    print(str(n) + " is a disarium number")  # Print if it's a disarium number
else:
    print(str(n) + " is not a disarium number")  # Print if it's not a disarium number
246 is not a disarium number

RAMANUJAN NUMBERS

Ramanujan Numbers are the numbers that can be expressed as sum of two cubes in two different ways. Therefore, Ramanujan Number $ (N) = a^{3} + b^{3} = c^{3} + d^{3}$

def ramanujan_On4(limit):
    result = ""

    for a in range(1, limit):
        for b in range(a, limit):
            for c in range(a, limit):
                for d in range(c, limit):

                    x = a ** 3 + b ** 3
                    y = c ** 3 + d ** 3

                    if x == y and (a != c or b != d):
                        number = a ** 3 + b ** 3
                        result += f'{number}: {a, b, c, d}\n'

    return result

L = 20
ra1_str = ramanujan_On4(L)
print(ra1_str)
1729: (1, 12, 9, 10)
4104: (2, 16, 9, 15)

Write a program that computes the value of a+aa+aaa+aaaa with a given digit as the value of a.

Suppose the following input is supplied to the program:
9
Then, the output should be:
11106
a = input()
n1 = int(f"{a}")
n2 = int(f"{a}{a}")
n3 = int(f"{a}{a}{a}")
n4 = int(f"{a}{a}{a}{a}")
print(n1 + n2 + n3 + n4)
9
11106

Write a program that computes the net amount of a bank account based a transaction log from console input. The transaction log format is shown as following:

D 100
W 200

D means deposit while W means withdrawal.
Suppose the following input is supplied to the program:
D 300
D 300
W 200
D 100
Then, the output should be:
500

netAmount = 0
while True:
    s = input()
    if not s:
        break
    
    # Initialize variables for operation and amount
    operation = ""
    amount_str = ""
    is_operation = True

    # Iterate over characters in the input string
    for char in s:
        if char == ' ':
            is_operation = False
        elif is_operation:
            operation += char
        else:
            # Convert the digit character to an integer
            digit_value = int(char) - int('0')
            amount_str += str(digit_value)

    # Convert the amount string to an integer
    amount = int(amount_str)

    # Perform the operation
    if operation == "D":
        netAmount += amount
    elif operation == "W":
        netAmount -= amount
    else:
        pass

print(netAmount)

nth value of fibonacci

def fibonacci(n):
    if n <= 0:
        return "Please enter a positive integer for n."
    elif n == 1:
        return 0
    elif n == 2:
        return 1
    else:
        return fibonacci(n - 1) + fibonacci(n - 2)

# Test the function
n = int(input("Enter the value of n: "))
result = fibonacci(n)
print(f"The {n}th value in the Fibonacci sequence is: {result}")
Enter the value of n: 5
The 5th value in the Fibonacci sequence is: 3

Write a function named format_number that takes a non-negative number as its only parameter.Your function should convert the number to a string and add commas as a thousands separator.

For example, calling format_number(1000000) should return "1,000,000".

def format_number(number):
    if number < 0:
        return "Please enter a non-negative number."

    result = ""

    count = 0
    while number > 0:
        digit = number % 10
        number //= 10

        if count == 3:
            result = "," + result
            count = 0

        result = str(digit) + result
        count += 1

    return result

# Test the function
num = 1000000
formatted_num = format_number(num)
print("Original Number:", num)
print("Formatted Number:", formatted_num)
Original Number: 1000000
Formatted Number: 1,000,000

Define a function param_count that takes a variable number of parameters. The function should return the number of arguments it was called with.

For example, param_count() should return 0, while param_count(2, 3, 4) should return 3.
def param_count(*args):
    count = 0
    for _ in args:
        count += 1
    return count

# Test the function
print(param_count())          # Output: 0
print(param_count(2, 3, 4))    # Output: 3
print(param_count('a', 'b'))   # Output: 2
0
3
2

Collatz Conjecture

A Collatz sequence is generated by repeatedly applying the following rules to an integer and then to each resulting integer in turn:

If even: divide by 2.
If odd: multiply by 3, then add 1.
The Collatz algorithm has been tested and found to always reach 1 for all positive integers.

Create a function that, when given two positive integers a b, returns the string "a" if integer a took fewer steps to reach 1 than b when passed through the Collatz sequence, or "b" if integer b took fewer steps to reach 1 than a.

def collatz_steps(n):
    steps = 0
    while n != 1:
        if n % 2 == 0:
            n = n // 2
        else:
            n = 3 * n + 1
        steps += 1
    return steps

def compare_collatz_steps(a, b):
    steps_a = collatz_steps(a)
    steps_b = collatz_steps(b)

    if steps_a < steps_b:
        return str(a)
    else:
        return str(b)

# Test the function
result = compare_collatz_steps(6, 9)
print(result)  # Output: "6"
6

TRIBONACCI SEQUENCE

def nthTribonacci(n):
    prev3 = 0
    prev2 = 0
    prev1 = 1
    
    print(prev3, prev2, prev1, end=" ")

    for i in range(4, n + 1):
        curr = prev1 + prev2 + prev3
        print(curr, end=" ")
        prev3 = prev2
        prev2 = prev1
        prev1 = curr

n = 20
print(f'The first {n} Tribonacci Numbers are:', end=" ")
nthTribonacci(n)
The first 20 Tribonacci Numbers are: 0 0 1 1 2 4 7 13 24 44 81 149 274 504 927 1705 3136 5768 10609 19513